<?php

class SiteController extends Controller
{

	public $navTitle="信息中心";

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules()
	{
		return array(
	            array('allow',
	                'actions'=>array('index','Setting'),
	                'users'=>array('@'),
	            ),
	            array('deny',
                	'users'=>array('*'),
	            ),
			);
	}
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$this->pageTitle='';
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	public function actionSetting()
	{
		$config= $this->loadConfig();
		if (Yii::app()->request->isPostRequest) {
			$logo =CUploadedFile::getInstanceByName('logo');
			if (isset($logo)) {
				$path=Yii::app()->params['upload'].'images/logo/'.$logo->getName();
				$logoname = Yii::getPathOfAlias('webroot').$path;
				if(!is_dir(dirname($logoname)))
				{
					if (!mkdir(dirname($logoname),0777,true)) {
						echo '创建文件夹失败';
					}
				}
				$logo->saveAs($logoname);
				$config=array_merge($config,array('logo'=>Yii::app()->baseUrl.$path));
				//array_push($config,'logo'=>$logoname);
			}
			$config=array_merge($config,$_POST);
			$this->SaveConfig($config);
			yii::app()->user->setFlash('success','操作成功');
			$this->refresh();
		}
		$this->render('setting',$config);
	}

	

	private function SaveConfig($config)
	{
		$siteconfig = Yii::app()->basePath.'/../config/'.'SiteConfig.php';
		$str = '<?php return ' . var_export($config, true) . ';';
		file_put_contents($siteconfig, $str);
	}

	private function loadConfig()
	{
		$siteconfig = Yii::app()->basePath.'/../config/'.'SiteConfig.php';
		if (!file_exists($siteconfig)) {
			$this->SaveConfig(array());
		}
		return require($siteconfig);
	}
}